import userData from '../data/users.json';

// 初始化用户数据到 localStorage（如果不存在）
const initializeUsers = () => {
  if (!localStorage.getItem('users')) {
    localStorage.setItem('users', JSON.stringify(userData.users));
  }
};

// 用户注册
export const register = (username, password, email) => {
  const users = JSON.parse(localStorage.getItem('users') || '[]');
  
  // 检查用户名是否已存在
  if (users.some(user => user.username === username)) {
    throw new Error('用户名已存在');
  }

  // 添加新用户
  const newUser = { username, password, email };
  users.push(newUser);
  localStorage.setItem('users', JSON.stringify(users));
  
  return { success: true, message: '注册成功' };
};

// 用户登录
export const login = (username, password) => {
  const users = JSON.parse(localStorage.getItem('users') || '[]');
  const user = users.find(u => u.username === username && u.password === password);

  if (user) {
    // 存储登录状态
    localStorage.setItem('currentUser', JSON.stringify({
      username: user.username,
      email: user.email
    }));
    return { success: true, message: '登录成功', user: { username: user.username, email: user.email } };
  } else {
    throw new Error('用户名或密码错误');
  }
};

// 用户登出
export const logout = () => {
  localStorage.removeItem('currentUser');
  return { success: true, message: '登出成功' };
};

// 获取当前登录用户
export const getCurrentUser = () => {
  const user = localStorage.getItem('currentUser');
  return user ? JSON.parse(user) : null;
};

// 检查是否已登录
export const isAuthenticated = () => {
  return !!localStorage.getItem('currentUser');
};

// 初始化
initializeUsers(); 